<template>
  <div>
    <!-- This is course page -->

    <!-- breadcrumb nav -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/manager' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>课程管理</el-breadcrumb-item>
        <el-breadcrumb-item>课程安排</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 查找课程：搜索框 -->
    <el-card class="search-bar">
      <el-row :gutter="20" type="flex" align="middle">
        <el-col :span="2" :offset="0">
          精准查找
        </el-col>
        <el-col :span="10" :offset="0">
          <el-input
          placeholder="请输入内容"
          v-model="searchValue"
          class="input-with-select"
          clearable>
            <el-select v-model="searchMethod" slot="prepend" placeholder="课程名称">
              <el-option label="课程名称" value="1"></el-option>
              <el-option label="学院名称" value="2"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="searchCourse()"></el-button>
          </el-input>
        </el-col>
      </el-row>
    </el-card>

    <!-- 课程列表 -->
    <el-card class="course-list">
      <el-button type="school" icon="el-icon-plus" @click="addCourseDrawer = true">添加课程</el-button>
      <el-button type="success" plain @click="MultiCourseDelete">删除</el-button>

      <!-- 所有的列表信息 -->
      <el-table
      :data="courseTable"
      style="width: 100%">
      <el-table-column
        type="selection"
        width="50">
      </el-table-column>
      <!-- 创建时间 -->
      <el-table-column
        label="创建时间"
        align="center"
        prop="create_time"
        width="">
      </el-table-column>
      <!-- 更新时间 -->
      <el-table-column
        label="更新时间"
        align="center"
        prop="update_time"
        width="140">
      </el-table-column>
      <!-- 书的封面图片 -->
      <el-table-column
        label="封面"
        align="center"
        width="180">
        <template slot-scope="scope">
          <!-- <img class="book-img" src="../../../assets/imgs/course/book.jpg" alt=""> -->
          <img class="book-img" :src="scope.row.bookCover">
        </template>
      </el-table-column>
      <!-- 课程名 -->
      <el-table-column
        label="课程名称"
        align="center"
        prop="name"
        width="140">
      </el-table-column>
      <el-table-column
        prop="semester"
        align="center"
        label="学期">
      </el-table-column>
      <el-table-column
        prop="score"
        align="center"
        label="学分">
      </el-table-column>
      <el-table-column
        prop="school"
        align="center"
        label="学院">
      </el-table-column>
      <el-table-column
        width="260"
        align="center"
        label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="expandSetCourseDrawer(scope.row)">排课</el-button>
          <el-button size="mini" @click="expandEditDrawer(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" plain @click="confirmDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
      </el-table>

      <!-- 分页导航 -->
      <el-pagination
        background
        @current-change="handleCurrentChange"
        :page-size="10"
        layout="total, prev, pager, next"
        :total="totalCourse">
      </el-pagination>
    </el-card>

    <!-- 删除课程的确认弹框 -->
    <el-dialog
      title="提示"
      :visible.sync="deleteDialogVisible"
      width="30%"
      :before-close="handleClose">
      <span>确认删除？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteCourse()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加课程的表单抽屉 -->
    <el-drawer
      class="add-course"
      title="添加课程表单"
      size="45%"
      :visible.sync="addCourseDrawer"
      :direction="drawerDirection"
      :before-close="handleClose">
      <el-form
        :model="addCourse"
        :rules="addCourseRules"
        ref="addCourseForm">
      <el-row :gutter="10">
        <!-- 开课学院： -->
        <el-col :span="12" :offset="0">
          <!-- <i>*</i> -->
          <el-form-item
            label="开课学院："
            :rules="[
              { required: true, message: '请输入开课学院' },
            ]">
            <el-select size="small" v-model="addschoolName" placeholder="请选择">
              <el-option
                v-for="item in schoolList"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <!-- <i>*</i> -->
          <el-form-item
            label="开课学期："
            prop="opeingSemester">
            <el-select size="small" v-model="addCourse.openingSemester" placeholder="请选择">
              <el-option
                v-for="item in semesterOpt"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12" :offset="0">
          <!-- <i>*</i> -->
          <!-- 课程名称： -->
          <el-form-item
            label="课程名称"
            prop="courseName">
            <el-input
              size="small"
              v-model="addCourse.courseName">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <!-- &nbsp;&nbsp;建议课时： -->
          <el-form-item
            label="建议课时："
            prop="classPeriod">
            <el-input
              size="small"
              v-model.number="addCourse.classPeriod">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12" :offset="0">
          <!-- <i>*</i> -->
          <!-- &nbsp;&nbsp;建议学分： -->
          <el-form-item
            label="建议学分："
            prop="credit">
            <el-input
              size="small"
              v-model="addCourse.credit">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="0">
        <el-col :span="4" :offset="0">
          <!-- 课程概述： -->
        </el-col>
        <el-col :span="19" :offset="0">
          <el-form-item
            label="课程概述："
            prop="courseDetail">
            <el-input
              :rows="3"
              type="textarea"
              v-model="addCourse.courseDetail">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="0">
        <el-col :span="4">
          <!-- 教学目标： -->
        </el-col>
        <el-col :span="19" :offset="0">
          <el-form-item
            label="教学目标："
            prop="instructionalObjectives">
            <el-input
              :rows="3"
              type="textarea"
              v-model="addCourse.instructionalObjectives">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="0">
        <el-col :span="4">
          <!-- <i>*</i> -->
          &nbsp;&nbsp;&nbsp;&nbsp;课程海报：
        </el-col>
        <el-col :span="19" :offset="0">
          <input type="file" accept="image/jpeg,image/jpg,image/png" @change="addUploadImg($event, previewImg)">
          <div style="text-align: top">
            <div style="font-size: 16px; margin-top: 10px">海报预览</div>
            <img v-if="previewImg" :src="previewImg" style="height: 200px; vertical-align: middle;" />
          </div>
        </el-col>
      </el-row>
      </el-form>

      <el-button type="school" class="submit" size="small" @click="addCourseSubmit()">提交</el-button>
      <el-button type="success" size="small" plain @click="refreshAddCourse()">取消</el-button>
    </el-drawer>

    <!-- 安排课程的表单抽屉 -->
    <el-drawer
      class="add-course"
      :title="currentCourse.name"
      size="45%"
      :visible.sync="setCourseDrawer"
      :direction="drawerDirection"
      :before-close="handleClose">
      <hr>
      <div class="setcoursetitle">课程详情</div>
      <el-row :gutter="10">
        <el-col :span="12" :offset="0">
          <i>*</i>
          开课学院：
          <el-input
            size="small"
            disabled
            v-model="currentCourse.school">
          </el-input>
        </el-col>
        <el-col :span="12" :offset="0">
          <i>*</i>
          开课学期：
          <el-input
            size="small"
            disabled
            v-model="currentCourse.semester">
          </el-input>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12" :offset="0">
          <i>*</i>
          课程名称：
          <el-input
            size="small"
            disabled
            v-model="currentCourse.name">
          </el-input>
        </el-col>
        <el-col :span="12" :offset="0">
          &nbsp;&nbsp;建议课时：
          <el-input
            size="small"
            disabled
            v-model="currentCourse.classPeriod">
          </el-input>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12" :offset="0">
          <!-- <i>*</i> -->
          &nbsp;&nbsp;建议学分：
          <el-input
            size="small"
            disabled
            v-model="currentCourse.score">
          </el-input>
        </el-col>
      </el-row>

      <el-row :gutter="0">
        <el-col :span="4" :offset="0">
          <i>*</i>
          课程概述：
        </el-col>
        <el-col :span="19" :offset="0">
          <el-input
            :rows="3"
            type="textarea"
            disabled
            v-model="currentCourse.courseDetail">
          </el-input>
        </el-col>
      </el-row>

      <el-row :gutter="0">
        <el-col :span="4">
          &nbsp;&nbsp;<i>*</i>
          教学目标：
        </el-col>
        <el-col :span="19" :offset="0">
          <el-input
            :rows="3"
            type="textarea"
            disabled
            v-model="currentCourse.instructionalObjectives">
          </el-input>
        </el-col>
      </el-row>

      <!-- 排课表单部分 -->
      <hr>
      <el-form
        :model="setCourseForm"
        :rules="setCourseRules"
        ref="setCourseForm">
      <div class="setcoursetitle">排课</div>
      <el-row :gutter="10">
        <el-col :span="12" :offset="0">
          <!-- 上课教师： -->
          <el-form-item
            label="上课教师："
            prop="teacherName">
            <el-select size="small" v-model="setCourseForm.teacherName" placeholder="请选择">
              <el-option
                v-for="item in teacherList"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <!-- 排课编号： -->
          <el-form-item
            label="排课编号："
            prop="courseTeacherNum">
            <el-input
              size="small"
              v-model.number="setCourseForm.courseTeacherNum">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-for="(time, index) in addTimeList" :key="index" :gutter="10">
        <el-col :span="12" :offset="0">
          <!-- &nbsp;&nbsp;上课时间： -->
          <el-form-item
            label="上课时间："
            :rules="[
              { required: 'true', message: '请选择上课时间', trigger: 'change' }
            ]">
            <el-select v-model="time.week" placeholder="请选择星期" size="small">
              <el-option label="" value="周一"></el-option>
              <el-option label="" value="周二"></el-option>
              <el-option label="" value="周三"></el-option>
              <el-option label="" value="周四"></el-option>
              <el-option label="" value="周五"></el-option>
              <el-option label="" value="周六"></el-option>
              <el-option label="" value="周日"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="0">
          <el-form-item
            label=""
            :rules="[
              { required: 'true', message: '请选择上课节次', trigger: 'change' }
            ]">
            <el-select v-model="time.section" placeholder="请选择节次" size="small">
              <el-option label="" value="1-2节"></el-option>
              <el-option label="" value="3-4节"></el-option>
              <el-option label="" value="5-6节"></el-option>
              <el-option label="" value="7-8节"></el-option>
              <el-option label="" value="9-10节"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <i class="el-icon-circle-plus" @click="addTimeValues"></i>
        </el-col>
        <el-col :span="2">
          <i class="el-icon-remove" @click="removeAddTime(time,index)"></i>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12" :offset="0">
          <!-- &nbsp;&nbsp;上课专业： -->
          <el-form-item
            label="上课专业："
            prop="class">
            <el-select v-model="setCourseForm.class" placeholder="请选择专业" size="small">
              <el-option
                v-for="item in majorList"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <!-- &nbsp;&nbsp;上课教室： -->
          <el-form-item
            label="上课教室："
            prop="classroom">
            <el-input
              size="small"
              v-model="setCourseForm.classroom">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12" :offset="0">
          <!-- &nbsp;&nbsp;课程分类： -->
          <el-form-item
            label="课程分类："
            prop="type">
            <el-select v-model="setCourseForm.type" placeholder="请选择类型" size="small">
              <el-option label="" value="必修课"></el-option>
              <el-option label="" value="选修课"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <!-- &nbsp;&nbsp;时间分类： -->
          <el-form-item
            label="时间分类："
            prop="timeType">
            <el-select v-model="setCourseForm.timeType" placeholder="请选择类型" size="small">
              <el-option label="每周都有" value="0"></el-option>
              <el-option label="单周" value="1"></el-option>
              <el-option label="双周" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12" :offset="0">
          <!-- &nbsp;&nbsp;实际课时： -->
          <el-form-item
            label="实际课时："
            prop="times">
            <el-input
              size="small"
              v-model.number="setCourseForm.times">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <!-- &nbsp;&nbsp;实际学分： -->
          <el-form-item
            label="实际学分："
            prop="score">
            <el-input
              size="small"
              v-model="setCourseForm.score">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <!-- <el-col :span="12" :offset="0">
          &nbsp;&nbsp;上课周期：
          <el-input
            size="small"
            v-model="setCourseForm.courseweek">
          </el-input>
        </el-col> -->
        <el-col :span="12" :offset="0">
          <!-- &nbsp;&nbsp;上课周期： -->
          <el-form-item
            label="上课周期："
            prop="weekStart">
            <el-select size="small" v-model="setCourseForm.weekStart" placeholder="开始">
              <el-option
                v-for="item in weekStart"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label=""
            prop="weekEnd">
            至&nbsp;&nbsp;&nbsp;&nbsp;
            <el-select size="small" v-model="setCourseForm.weekEnd" placeholder="结束">
              <el-option
                v-for="item in weekEnd"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
            &nbsp;&nbsp;周
          </el-form-item>
        </el-col>
      </el-row>

      <el-button type="school" class="submit" size="small" @click="setCourseSubmit()">提交</el-button>
      <el-button type="success" size="small" plain @click="setCourseDrawer = false">取消</el-button>
      </el-form>
      <br><br>
    </el-drawer>

    <!-- 修改课程的表单抽屉 -->
    <el-drawer
      class="add-course"
      :title="currentCourse.name"
      size="45%"
      :visible.sync="editCourseDrawer"
      :direction="drawerDirection"
      :before-close="handleClose">
      <el-form
        :model="currentCourse"
        :rules="editCourseRules"
        ref="editCourseForm">
        <el-row :gutter="10">
          <el-col :span="12" :offset="0">
            <!-- <i>*</i> -->
            <!-- 开课学院： -->
            <el-form-item
              label="开课学院："
              prop="school">
              <el-select size="small" v-model="currentCourse.school" placeholder="请选择开课学院">
                <el-option
                  v-for="item in schoolList"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <!-- <i>*</i> -->
            <!-- 开课学期： -->
            <el-form-item
              label="开课学期："
              prop="semester">
              <el-select size="small" v-model="currentCourse.semester" placeholder="请选择开课学期">
                <el-option
                  v-for="item in semesterOpt"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="12" :offset="0">
            <!-- <i>*</i> -->
            <!-- 课程名称： -->
            <el-form-item
            label="课程名称"
            prop="name">
              <el-input
                size="small"
                v-model="currentCourse.name">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <!-- &nbsp;&nbsp;建议课时： -->
            <el-form-item
            label="建议课时："
            prop="classPeriod">
              <el-input
                size="small"
                v-model.number="currentCourse.classPeriod">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="12" :offset="0">
            <!-- <i>*</i> -->
            <!-- &nbsp;&nbsp;建议学分： -->
            <el-form-item
              label="建议学分："
              prop="score">
              <el-input
                size="small"
                v-model="currentCourse.score">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="0">
          <el-col :span="4" :offset="0">
            <!-- <i>*</i> -->
            <!-- 课程概述： -->
          </el-col>
          <el-col :span="19" :offset="0">
            <el-form-item
              label="课程概述："
              prop="courseDetail">
              <el-input
                :rows="3"
                type="textarea"
                v-model="currentCourse.courseDetail">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="0">
          <el-col :span="4">
            <!-- &nbsp;&nbsp;<i>*</i>
            教学目标： -->
          </el-col>
          <el-col :span="19" :offset="0">
            <el-form-item
              label="教学目标："
              prop="instructionalObjectives">
              <el-input
                :rows="3"
                type="textarea"
                v-model="currentCourse.instructionalObjectives">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="0">
          <el-col :span="4">
            <!-- <i>*</i> -->
            &nbsp;&nbsp;&nbsp;&nbsp;课程海报：
          </el-col>
          <el-col :span="19" :offset="0">
            <img :src="currentCourse.bookCover" :v-for="currentCourse.bookCover" style="height: 200px;">
            <img v-if="changeImg" :src="changeImg" style="height: 200px; vertical-align: middle;" />
            <input type="file" accept="image/jpeg,image/jpg,image/png" @change="changeImgUpload($event)">
          </el-col>
        </el-row>

        <el-button type="school" class="submit" size="small" @click="editCourseSubmit()">提交</el-button>
        <el-button type="success" size="small" plain @click="editCourseDrawer = false">取消</el-button>
      </el-form>
    </el-drawer>

  </div>
</template>

<script>
import { toDateString } from '@/utils/time.js'
import { getAllMajors, getAllTeachers, getAllSchools } from '@/utils/dropdown.js'
export default {
  data () {
    // 验证教室格式
    var checkClassroom = (rule, value, cb) => {
      // 教的unicode码就是\u6559
      const regRoom = /^(\u6559)[\u4e09,\u56db,\u4e94]\d(0|1)\d$/

      if (regRoom.test(value)) {
        return cb()
      }

      cb(new Error('请输入正确的教室名，样例格式：教三101'))
    }

    // 验证学分的格式
    var checkCredit = (rule, value, cb) => {
      // 教的unicode码就是\u6559
      const regRoom = /^\d\.(0|5)$/

      if (regRoom.test(value)) {
        return cb()
      }

      cb(new Error('请输入正确的学分格式, 样例格式：3.0'))
    }

    return {
      // 添加课程的表单验证
      addCourseRules: {
        openingSemester: [
          { required: true, message: '请选择开课学期', trigger: 'blur' }
        ],
        courseName: [
          { required: true, message: '请输入课程名称', trigger: 'blur' }
        ],
        classPeriod: [
          { required: true, message: '请输入建议课时', trigger: 'blur' },
          { type: 'number', message: '建议课时必须是数字', trigger: 'blur' }
        ],
        credit: [
          { required: true, message: '请输入建议学分', trigger: 'blur' },
          { validator: checkCredit, trigger: 'blur' }
        ],
        courseDetail: [
          { required: true, message: '请输入课程概述', trigger: 'blur' }
        ],
        instructionalObjectives: [
          { required: true, message: '请输入教学目标', trigger: 'blur' }
        ]
      },

      // 编辑课程的验证
      editCourseRules: {
        school: [
          { required: true, message: '请选择开课学院', trigger: 'blur' }
        ],
        semester: [
          { required: true, message: '请选择开课学期', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入课程名称', trigger: 'blur' }
        ],
        classPeriod: [
          { required: true, message: '请输入建议课时', trigger: 'blur' },
          { type: 'number', message: '建议课时必须是数字', trigger: 'blur' }
        ],
        score: [
          { required: true, message: '请输入建议学分', trigger: 'blur' },
          { validator: checkCredit, trigger: 'blur' }
        ],
        courseDetail: [
          { required: true, message: '请输入课程概述', trigger: 'blur' }
        ],
        instructionalObjectives: [
          { required: true, message: '请输入教学目标', trigger: 'blur' }
        ]
      },

      // 排课表单验证
      setCourseRules: {
        teacherName: [
          { required: true, message: '请输入上课教师', trigger: 'change' }
        ],
        courseTeacherNum: [
          { required: true, message: '请输入课程编号', trigger: 'blur' },
          { type: 'number', message: '请填写数字编号', trigger: 'blur' }
        ],
        class: [
          { required: true, message: '请输入上课专业', trigger: 'blur' }
        ],
        classroom: [
          { required: true, message: '请输入上课教室', trigger: 'blur' },
          { validator: checkClassroom, trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择课程分类', trigger: 'blur' }
        ],
        timeType: [
          { required: true, message: '请选择时间分类', trigger: 'blur' }
        ],
        times: [
          { required: true, message: '请输入实际课时', trigger: 'blur' },
          { type: 'number', message: '课时必须是数字', trigger: 'blur' }
        ],
        score: [
          { required: true, message: '请输入实际学分', trigger: 'blur' },
          { validator:checkCredit, trigger: 'blur' }
        ],
        weekStart: [
          { required: true, message: '请选择开始周次', trigger: 'blur' }
        ],
        weekEnd: [
          { required: true, message: '请选择结束周次', trigger: 'blur' }
        ]
      },

      // 课程列表数据
      courseTable: [],
      // courseTable: [{
      //   id: 1,
      //   name: '数据结构',
      //   semester: '2',
      //   score: '2',
      //   school: '计算机与信息工程学院'
      // }],
      // 搜索框部分
      searchValue: '',
      searchMethod: '1',
      // 删除弹框
      deleteDialogVisible: false,
      deleteCourseId: 0,
      // 当前课程记录
      currentCourse: {},
      // 添加课程抽屉部分
      addCourseDrawer: false,
      setCourseDrawer: false,
      editCourseDrawer: false,
      drawerDirection: 'rtl', // 代表从左到右RightToLeft
      // 添加课程的数据
      addCourse: {
        classPeriod: '',
        courseDetail: '',
        courseName: '',
        credit: '',
        instructionalObjectives: '',
        openingSemester: ''
      },

      // 第几学期的选项框
      semesterOpt: [1, 2, 3, 4, 5, 6, 7, 8],
      addschoolName: '',
      // 添加的图片
      addPic: '', // 但是添加图片的格式是FormData数据
      // 添加课程的预览的图片
      previewImg: '', // 预览图片的格式是URL
      // 修改课程的图片
      changePic: '',
      // 修改课程的预览图片
      changeImg: '',
      currentPage: 1,
      totalCourse: 100,
      setCourseForm: {
        teacherName: '',
        class: '',
        type: '',
        times: '',
        score: '',
        classroom: '',
        courseTeacherNum: '',
        timeType: 0,
        weekStart: 0,
        weekEnd: 0
      },
      addTimeList: [{
        week: '',
        section: ''
      }],
      // 设定上课周期的选择值
      weekStart: [1, 2, 3, 4, 5, 6, 7, 8, 9],
      weekEnd: [8, 9, 10, 11, 12, 13, 14, 15, 16],
      // 数据库中的学院，教师，专业
      schoolList: [],
      majorList: [],
      teacherList: []
    }
  },
  async created () {
    this.getCourseList()

    this.majorList = await getAllMajors()
    // console.log(this.majorList)
    this.schoolList = await getAllSchools()
    // console.log(this.schoolList)
    this.teacherList = await getAllTeachers()
  },
  methods: {
    handleClose (done) {
      // this.$confirm('确认关闭？')
      //   .then(_ => {
      //     done();
      //   })
      //   .catch(_ => {});
      this.changeImg = ''
      this.previewImg = ''
      done()
    },

    // 搜索所有匹配到的课程
    async searchCourse () {
      // 通过课程名搜索
      this.getCourseList()
    },

    // 获取所有的课程
    // 相当于页面中的那个选择方式为全局的变量改变
    async getCourseList () {
      if (this.searchMethod == 1) {
        const { data: res } = await this.$http.post(`course/all/getCourseList?page=${this.currentPage - 1}&rows=10&courseName=${this.searchValue}`)
        console.log(res)
        if (!res.state) return
        this.courseTable = []
        this.foreachObj(res.detail)
        this.totalCourse = res.detail.total
      }
      // 通过学院名搜索
      else if (this.searchMethod == 2) {
        const { data: res } = await this.$http.post(`course/all/getCourseList?page=${this.currentPage - 1}&rows=10&schoolName=` + this.searchValue)
        console.log(res)
        if (!res.state) return
        this.courseTable = []
        this.foreachObj(res.detail)
        this.totalCourse = res.detail.total
      }
    },

    // 新增课程上传图片函数
    addUploadImg (e) {
      const file = e.target.files[0]
      if (file.length == 0) {
        this.previewImg = ''
        return
      }
      // 使用 FileReader 读取文件对象
      const reader = new FileReader()
      // 读取完毕后获取结果，写入到previewImg中
      reader.onload = event => {
        this.previewImg = event.target.result
      }
      // 把文件对象作为一个 dataURL 读入
      reader.readAsDataURL(file)
      // 创建FormData
      const param = new FormData() // 创建form对象
      param.append('file', file, file.name) // 通过append向form对象添加数据
      console.log(param.get('file')) // FormData私有类对象，访问不到，可以通过get判断值是否传进去
      this.addPic = param
    },

    // 修改课程上传图片函数
    changeImgUpload (e) {
      const file = e.target.files[0]
      if (file.length == 0) {
        this.changeImg = ''
        return
      }
      // 使用 FileReader 读取文件对象
      const reader = new FileReader()
      // 读取完毕后获取结果，写入到changeImg中
      reader.onload = event => {
        this.changeImg = event.target.result
      }
      this.currentCourse.bookCover = ''
      // 把文件对象作为一个 dataURL 读入
      reader.readAsDataURL(file)
      const param = new FormData() // 创建form对象
      param.append('file', file, file.name) // 通过append向form对象添加数据
      console.log(param.get('file')) // FormData私有类对象，访问不到，可以通过get判断值是否传进去
      this.changePic = param
    },

    // 添加一个课程
    addCourseSubmit () {
      this.$refs.addCourseForm.validate(valid => {
        if (!valid) return
        this.$http({
          method: 'post',
          url: 'course/admin/createCourse?schoolName=' + this.addschoolName,
          data: this.addCourse
        }).then(async res => {
          // console.log(res)
          if (!res.data.state) return this.$message.error(res.data.msg)
          if (this.addPic) {
          // 接入另一个传入课程图片的接口
            console.log(this.addPic.get('file'))
            const config = {
              headers: {
                'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime()
              }
            }
            const { data: respon } = await this.$http.post('course/admin/courseAvatar?id=' + res.data.detail.id, this.addPic, config)
            console.log(respon)
            if (!respon.state) return this.$message.error(respon.msg)
          }
          this.$message.success('添加课程成功！')
          // 添加课程成功之后的后续初始工作
          this.refreshAddCourse()
          this.getCourseList()
          // 最后还需要将previewImg置空
          this.previewImg = ''
        }).catch(err => {
          console.log(err)
        })
      })
    },

    // 取消添加课程
    refreshAddCourse () {
      var addCourse = {
        classPeriod: '',
        courseDetail: '',
        courseName: '',
        credit: '',
        instructionalObjectives: '',
        openingSemester: ''
      }
      this.addCourse = addCourse
      this.addCourseDrawer = false
    },

    // 删除多个课程
    MultiCourseDelete () {
    },

    // 弹出删除框
    confirmDelete (id) {
      this.deleteDialogVisible = true
      this.deleteCourseId = id
    },

    // 删除单个课程
    async deleteCourse () {
      const { data: res } = await this.$http.post('course/admin/deleteCourse?id=' + this.deleteCourseId)
      if (!res.state) return this.$message.error('删除失败！')
      this.$message.success('删除课程成功！')
      this.deleteDialogVisible = false
      this.getCourseList()
    },

    // 展开当前课程进行修改
    expandEditDrawer (course) {
      this.editCourseDrawer = true
      // 将当前的课程改为选中的课程
      course.classPeriod = parseInt(course.classPeriod)
      this.currentCourse = course
      // console.log(this.currentCourse)
    },

    // 对修改的课程表单进行提交
    editCourseSubmit () {
      this.$refs.editCourseForm.validate(valid => {
        if (!valid) return
        var course = {
          avatarUrl: 'http://101.34.38.114/imgs/course_OS.png',
          classPeriod: '',
          courseDetail: '',
          courseName: '',
          credit: '',
          instructionalObjectives: '',
          openingSemester: '',
          id: ''
        }
        // currentCourse是表单中的数据
        course.id = this.currentCourse.id
        course.avatarUrl = this.currentCourse.bookCover
        course.openingSemester = this.currentCourse.semester
        course.courseName = this.currentCourse.name
        course.classPeriod = this.currentCourse.classPeriod
        course.credit = this.currentCourse.score
        course.courseDetail = this.currentCourse.courseDetail
        course.instructionalObjectives = this.currentCourse.instructionalObjectives
        this.$http({
          method: 'post',
          url: 'course/admin/updateCourse?schoolName=' + this.currentCourse.school,
          data: course
        }).then(async res => {
          console.log(res)
          if (!res.data.state) return this.$message.error(res.data.msg)
          // 如果有改图片就调用传入图片接口
          if (this.changePic) {
            // 接入另一个传入课程图片的接口
            console.log(this.changePic.get('file'))
            const config = {
              headers: {
                'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime()
              }
            }
            const { data: respon } = await this.$http.post('course/admin/courseAvatar?id=' + res.data.detail.id, this.changePic, config)
            console.log(respon)
            if (!respon.state) return this.$message.error("修改图片出错！")
            // 添加课程成功之后的后续初始工作
            this.refreshAddCourse()
            this.getCourseList()
            // 最后还需要将changeImg置空
            this.changeImg = ''
          }
          this.$message.success('修改课程成功！')
          this.currentCourse = {}
          this.editCourseDrawer = false
          this.getCourseList()
        }).catch(err => {
          console.log(err)
        })
      })
    },

    // 展开当前课程进行排课
    expandSetCourseDrawer (course) {
      this.setCourseForm = {
        teacherName: '',
        class: '',
        type: '',
        times: '',
        score: '',
        classroom: '',
        courseweek: '',
        courseTeacherNum: ''
      },
      this.addTimeList = [{
        week: '',
        section: ''
      }]
      this.setCourseDrawer = true
      // 将当前的课程改为选中的课程
      this.currentCourse = course
      // console.log(this.currentCourse)
    },

    // 对排课信息进行提交
    setCourseSubmit () {
      this.$refs.setCourseForm.validate(valid => {
        if (!valid) return
        var course = {
          classCycle: '', // 1-16周
          classPeriod: '', // 64学时
          classroom: '', // 教三201
          credict: '', // 2分
          genre: '', // 选修课
          courseTeacherNum: '', // 20024
          courseName: '', // asp.net程序设计
          teacherName: '', // 曾诚
          className: '' // 软件工程
        }
        // 将所有的字段填到json数据中
        // 首先上课周期是三个元素拼接到一起的，所以先处理
        course.classCycle = this.setCourseForm.weekStart + ' ' + this.setCourseForm.weekEnd + ' ' + this.setCourseForm.timeType
        course.classPeriod = this.setCourseForm.times
        course.classroom = this.setCourseForm.classroom
        course.credict = this.setCourseForm.score
        course.genre = this.setCourseForm.type
        course.courseTeacherNum = this.setCourseForm.courseTeacherNum
        course.courseName = this.currentCourse.name
        course.teacherName = this.setCourseForm.teacherName
        course.className = this.setCourseForm.class
        // 因为这里的课程一周里面可能会有多节课，
        // 所以我们应该设置一个section的list结构
        // 来传递courseTimeList
        var url = 'courseManagement/admin/createCourseManagement?courseTimeList='
        this.addTimeList.forEach((item, index) => {
          url += item.week + item.section
          if (index != this.addTimeList.length - 1) {
            url += '&courseTimeList='
          }
        })
        // console.log(url);
        this.$http({
          method: 'post',
          url: url,
          data: course
        }).then(res => {
          const data = res.data
          console.log(data)
          if (!data.state) return this.$message.error(data.msg)
          this.$message.success('排课成功！')
          this.setCourseForm = {
            teacherName: '',
            class: '',
            type: '',
            times: '',
            score: '',
            classroom: '',
            courseTeacherNum: '',
            timeType: 0,
            weekStart: 0,
            weekEnd: 0
          },
          this.setCourseDrawer = false
        })
      })
    },

    //
    //// 增加一个时间及其所有值
    //
    // 向字典表单里面添加一个value值
    addTimeValues () {
      this.addTimeList.push({
        week: '',
        section: ''
      })
    },
    // 移除一个value值
    removeAddTime (value, index) {
      if (value.week !== undefined) {
        if (this.addTimeList.length > 1) {
          this.addTimeList.splice(index, 1)
        } else {
          this.addTimeList = [
            {
              week: '',
              section: ''
            }
          ]
        }
      }
    },

    // 更改页码，进行导航
    async handleCurrentChange (val) {
      // console.log(val)
      this.currentPage = val
      this.getCourseList()
    },
    foreachObj (data) {
      data.list.forEach(item => {
        var obj = {
          id: 0,
          name: '',
          semester: '',
          score: '',
          school: '',
          bookCover: '',
          courseDetail: '',
          instructionalObjectives: '',
          classPeriod: '',
          create_time: '',
          update_time: ''
        }
        obj.id = item.id
        obj.name = item.course_name
        obj.semester = item.opening_semester
        obj.score = item.credit
        obj.school = item.school_name
        obj.bookCover = item.avatar_url
        obj.courseDetail = item.course_detail
        obj.instructionalObjectives = item.instructional_objectives
        obj.classPeriod = item.class_period
        obj.create_time = toDateString(item.create_time)
        obj.update_time = toDateString(item.update_time)
        this.courseTable.push(obj)
      })
    }
  }
}
</script>

<style lang="less" scoped>
.search-bar {
  margin-top: 20px;

  .el-select /deep/ .el-input {
    width: 110px;
  }
}

.course-list {
  margin-top: 20px;

  .el-table {

    .book-img {
      height: 100px;
    }
  }

  .el-pagination {
    margin: 12px 0;
    float: right;
  }
}

.add-course {
  font-size: 14px;

  .el-row {
    margin-left: 10px !important;
    margin-bottom: 20px;

    i {
      color: red;
    }

    .el-input {
      width: 200px;
    }
  }

  .el-button.submit {
    margin-left: 120px;
  }
}

.setcoursetitle {
  padding: 20px;
  padding-top: 0px;
  color: rgb(137, 144, 145);
}
</style>
